﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Interface.Api;

namespace yafc.DataPool
{
	class PostPool
	{
		#region Fields

		private Dictionary<string, Post> oldp = new Dictionary<string,Post>();
		private Dictionary<string, Post> newp = new Dictionary<string,Post>();

		#endregion

		#region Public Properties

		public ICollection<Post> NewPosts
		{
			get
			{
				ICollection<Post> result;
				lock (newp)
				{
					result = newp.Values.ToArray();
					newp.Clear();
				}
				add2Old(result);
				return result;
			}
		}

		public ICollection<Post> OldPosts
		{
			get
			{
				lock (oldp)
				{
					return oldp.Values;
				}
			}
		}

		public ICollection<Post> AllPosts
		{
			get
			{
				ICollection<Post> olds, news;
				lock(oldp)
				{
					olds = oldp.Values;
				}
				lock(newp)
				{
					news = newp.Values;
				}
				return olds.Concat(news).ToArray();
			}
		}

		#endregion

		#region Constructors
		#endregion

		#region Public Methods

		public void addPost(ICollection<Post> Posts)
		{
			lock(oldp)
			{
				foreach (Post p in Posts)
				{
					if (oldp.ContainsKey(p.id))
					{
						// Mark here.
						p.id = null;
					}
				}
			}
			lock(newp)
			{
				foreach (Post p in Posts)
				{
					if (p.id != null && !newp.ContainsKey(p.id))
					{
						newp.Add(p.id, p);
					}
				}
			}
		}

		#endregion

		#region Non-Public Methods

		private void add2Old(ICollection<Post> Posts)
		{
			lock(oldp)
			{
				foreach (Post p in Posts)
				{
					oldp.Add(p.id, p);
				}
			}
		}

		#endregion
	}
}
